<template>
  <div class="dealerApply sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="经销商名称:">
              <el-input v-model="query.dealerName" placeholder="请输入经销商名称" clearable/>
            </el-form-item>
            <el-form-item label="经销商类型:">
              <el-select v-model="query.category" placeholder="请选择" clearable>
                <el-option label="门店经销商" value="1" />
                <el-option label="区/县运营中心" value="2" />
                <el-option label="市运营中心" value="3" />
                <el-option label="省运营中心" value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态:">
              <el-select v-model="query.applyStatus" placeholder="请选择" clearable>
                <el-option label="待审核" value="0" />
                <el-option label="通过" value="1" />
                <el-option label="驳回" value="2" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="经销商申请数据" icon="Histogram" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中">
        <el-table ref="tableRef" :data="dataList" max-height="493" border>
          <el-table-column label="序号" type="index" align="center" width="60"/>
          <el-table-column label="编号" prop="dealersId" align="center" width="180"></el-table-column>
          <el-table-column label="姓名" prop="dealerName" align="center"></el-table-column>
          <el-table-column label="加盟费/保证金" prop="joinFee" align="center"></el-table-column>
          <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
          <el-table-column label="类型" prop="category" align="center">
            <template #default="{row}">
              <span v-if="row.category === '1'">门店经销商</span>
              <span v-if="row.category === '2'">区/县运营中心</span>
              <span v-if="row.category === '3'">市运营中心</span>
              <span v-if="row.category === '4'">省运营中心</span>
            </template>
          </el-table-column>
          <el-table-column label="区域" prop="name" align="center" show-overflow-tooltip>
            <template #default="{row}">
              <span>{{ row.provinceName + row.cityName + row.regionName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="applyStatus" align="center">
            <template #default="{row}">
              <el-tag v-if="row.applyStatus === 0" type="info">待审核</el-tag>
              <el-tag v-if="row.applyStatus === 1" type="success">通过</el-tag>
              <el-tag v-if="row.applyStatus === 2" type="danger">驳回</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="驳回理由" prop="rejectReason" align="center"></el-table-column>
          <el-table-column label="创建时间" prop="createdTime" align="center" width="170">
            <template #default="{row}">
              <span>{{ $date(row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template #default="{row}">
              <el-button type="primary" icon="View" link @click="toView(row.dealerApplyId)">详情</el-button>
              <el-divider v-if="row.applyStatus === 0" direction="vertical" />
              <el-button v-if="row.applyStatus === 0" type="success" icon="SuccessFilled" link @click="toExamine(row.dealerApplyId, true)">通过</el-button>
              <el-divider v-if="row.applyStatus === 0" direction="vertical" />
              <el-button v-if="row.applyStatus === 0" type="danger" icon="RefreshRight" link @click="toExamine(row.dealerApplyId, false)">驳回</el-button>
              <el-divider v-if="row.applyStatus === 0" direction="vertical" />
              <el-button v-if="row.applyStatus === 0" type="danger" icon="Delete" link @click="doDelete(row.dealerApplyId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增弹窗 -->
    <el-dialog v-model="show" title="新增" top="10vh" width="32.6%" destroy-on-close center draggable class="save-dialog" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="large" label-position="right" label-width="125px">
        <el-form-item label="推广员:" prop="dealersId" required>
          <el-select
            v-model="form.dealersId"
            filterable
            remote
            remote-show-suffix 
            clearable 
            placeholder="请输入会员名称或编号查询"
            :remote-method="loadPromoter"
            :loading="selectLoading">
            <el-option v-for="item in promoters" :key="item.dealersId" :label="item.memberName" :value="item.dealersId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="经销商类型:" prop="category">
          <el-select v-model="form.category" placeholder="请选择经销商类型" @change="loadRules">
            <el-option label="门店经销商" :value="1" />
            <el-option label="区/县运营中心" :value="2" />
            <el-option label="市运营中心" :value="3" />
            <el-option label="省运营中心" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="区域:" prop="region" required>
          <region-select v-model="form.region" size="large" ref="regionRef"></region-select>
        </el-form-item>
        <el-form-item label="经销商注册规则:" prop="ruleId" required>
          <el-select v-model="form.ruleId" placeholder="请选择经销商注册规则" clearable>
            <el-option v-for="item in ruleList" :key="item.ruleId" :label="item.ruleName" :value="item.ruleId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称:" prop="companyName" required>
          <el-input v-model="form.companyName" placeholder="请输入公司名称" clearable/>
        </el-form-item>
        <el-form-item label="联系电话:" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" clearable/>
        </el-form-item>
        <el-form-item label="姓名:" prop="dealerName" required>
          <el-input v-model="form.dealerName" placeholder="请输入真实姓名" clearable/>
        </el-form-item>
        <el-form-item label="身份证号码:" prop="idCard" required>
          <el-input v-model="form.idCard" placeholder="请输入身份证号码" clearable/>
        </el-form-item>
        <el-form-item label="身份证附件:" prop="idCardFront" required>
          <upload-img v-model="form.idCardFront" width="400" height="220" uploadIcon="zcytIcon zcyt-shenfenzhengzhengmian" iconSize="100"></upload-img>
        </el-form-item>
        <el-form-item label="" prop="idCardBack" required>
          <upload-img v-model="form.idCardBack" width="400" height="220" uploadIcon="zcytIcon zcyt-shenfenzhengfanmian" iconSize="100"></upload-img>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSave">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="infoShow" :with-header="false" :destroy-on-close="true" size="89.6%">
      <dealer-apply-details :dealerApplyId="dealerApplyId" @close="doChose"></dealer-apply-details>
    </el-drawer>
  </div>
</template>

<script setup name="dealerApply">
  import dealerApplyDetails from './details.vue'
  import { 
    saveDealerApplyApi, 
    getDealerApplyListPagesApi, 
    deleteDealerApplyApi, 
    updateDealerApplyStatusApi, 
    getPromoterListApi,
    getRegisterRuleListApi
  } from '@/api/api'
  import { regexPhone, regexIdCard } from '@/utils/utils'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties

  const formRef = ref(null)
  const regionRef = ref(null)

  const currentData = reactive({
    loading: false,
    selectLoading: false,
    show: false,
    infoShow: false,
    query: {
      dealerName: '',
      category: '',
      applyStatus: '',
      current: 1,
      size: 20,
      total: 0
    },
    form: {
      dealersId: '',
      category: 1,
      companyName: '',
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      phone: '',
      dealerName: '',
      idCard: '',
      idCardFront: '',
      idCardBack: '',
      ruleId: '',
      region: []
    },
    examineForm: {
      dealerApplyId: '',
      applyStatus: '',
      rejectReason: ''
    },
    rules: {
      companyName: [{ required: true, message: '请输入公司名称', trigger: ['blur', 'change'] }],
      dealerName: [{ required: true, message: '请输入真实姓名', trigger: ['blur', 'change'] }],
      idCard: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入身份证号'))
            } else {
              if(!regexIdCard(value)) {
                callback(new Error('请输入正确的身份证号'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      idCardFront: [{ required: true, message: '请上传身份证正面', trigger: 'blur' }],
      idCardBack: [{ required: true, message: '请上传身份证反面', trigger: 'blur' }],
      ruleId: [{ required: true, message: '请选择经销商注册规则', trigger: 'blur' }],
      phone: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入手机号码'))
            } else {
              if(!regexPhone(value)) {
                callback(new Error('手机号码格式不对，且必须是11位'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      region: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value.length) {
              callback(new Error('请选择省、市、区县'))
            } else if(value.length === 1) {
              callback(new Error('请选择市、区县'))
            } else if(value.length === 2) {
              callback(new Error('请选择区县'))
            } else if(value.length === 3) {
              callback()
            }
          } 
        }
      ]
    },
    dealerApplyId: '',
    dataList: [],
    promoters: [],
    ruleList: []
  })
  let {loading, selectLoading, show, infoShow, query, form, examineForm, rules, dealerApplyId, dataList, promoters, ruleList} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getDealerApplyListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增时候推广员下拉选择数据根据输入值查询
  function loadPromoter(dealer) {
    if(!dealer) {
      return
    }
    currentData.selectLoading = true
    getPromoterListApi({ dealer: dealer }).then(res => {
      currentData.selectLoading = false
      if(res.code === '200') {
        currentData.promoters = res.data
      }
    })
  }

  function doSave() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm('确认新增吗？').then(() => {
          let loading = currentThis.$loading('正在新增，请耐心等待')
          currentData.form.provinceCode = currentData.form.region[0]
          currentData.form.cityCode = currentData.form.region[1]
          currentData.form.regionCode = currentData.form.region[2]
          saveDealerApplyApi(currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              load(currentData.query.current)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  function toView(dealerApplyId) {
    currentData.dealerApplyId = dealerApplyId
    currentData.infoShow = true
  }

  // 审核通过或驳回弹窗确认
  function toExamine(dealerApplyId, e) {
    currentData.examineForm = {dealerApplyId: dealerApplyId, applyStatus: e ? 1 : 2, rejectReason: ''}
    if(e) {
      currentThis.$messageBox.confirm('确认通过吗？').then(() => {
        doExamine()
      }).catch(() => {})
    } else {
      currentThis.$messageBox.prompt('驳回原因', '确认驳回吗？').then(({value}) => {
        currentData.examineForm.rejectReason = value
        doExamine()
      }).catch(() => {})
    }
  }
  // 执行审核
  function doExamine() {
    const loading = currentThis.$loading('正在处理，请耐心等待')
    updateDealerApplyStatusApi(currentData.examineForm).then(res => {
      loading.close()
      if(res.code === '200') {
        load(currentData.query.current)
        currentThis.$message.success(res.message)
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 删除
  function doDelete(dealersId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('正在删除，请耐心等待')
      deleteDealerApplyApi({ id: dealersId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 关闭详情
  function doChose() {
    load(currentData.query.current)
    currentData.infoShow = false
  }
  
  // 重置查询
  function resetSearch() {
    currentData.query.dealerName = ''
    currentData.query.category = ''
    currentData.query.applyStatus = ''
    load(1)
  }

  // 新增编辑弹窗重置数据
  function resetForm() {
    currentData.form = {
      dealersId: '',
      category: 1,
      companyName: '',
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      phone: '',
      dealerName: '',
      idCard: '',
      idCardFront: '',
      idCardBack: '',
      ruleId: '',
      region: []
    }
    formRef.value.resetFields()
    regionRef.value.resetData()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  // 初始化经销商注册规则下拉数据
  function loadRules() {
    getRegisterRuleListApi({ registerType: currentData.form.category}).then(res => {
      if(res.code === '200') {
        currentData.ruleList = res.data
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  onActivated(() => {
    load(currentData.query.current)
    loadRules()
  })
</script>

<style lang="less" scoped>
.dealerApply{
  :deep(.save-dialog.el-dialog){
    .el-dialog__body{
      max-height: 500px;
      overflow: hidden auto;
      .el-form-item__content{
        >.el-input{
          width: 300px;
        }
      }
      .idCard_upload{
        width: 400px; 
        height: 200px;
        border-radius: 8px;
        border: 1px dashed #DCDFE6;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 100px;
        color: #DCDFE6;
        &:hover{
          border-color: #409EFF;
        }
        span{
          color: #8a8b8b;
        }
      }
    }
  }
  :deep(.el-drawer){
    .el-drawer__body{
      padding: 0 20px !important;
    }
  }
}
</style>